<?php

/* empty stubs for now */
function cable_index_load($connector)
{
	return true;
}

function cable_index_unload($connector)
{
	return true;
}

function cable_index_open(&$connector)
{
	/* plugin opening routine has no caching behavior */
	if ($connector->data[cached])
		return true;

	/* import and initialize plugin global array */
	global $cable_index_plugin;
	$cable_index_plugin = array('fail'=>true);

	/* initialization */
	$cable_index_plugin[connector] = &$connector;
	$cable_index_plugin[author_names] = array();
	$cable_index_plugin[timestamps] = array();
	$cable_index_plugin[current_day] = -1;
	$cable_index_plugin[current_month] = -1;
	$cable_index_plugin[next_entry]	= false;
	$cable_index_plugin[previous_entry]	= false;
	
	/* retrieve plugin templates */
	$cable_index_plugin[month_template] = $connector->template->GetChild('CABLE-Month');
	if ($cable_index_plugin[month_template] === false)
		return 'Error retrieving index month template';

	$cable_index_plugin[day_template] = $cable_index_plugin[month_template]->GetChild('CABLE-Day');
	if ($cable_index_plugin[day_template] === false)
		return 'Error retrieving index day template';
		
	$cable_index_plugin[entry_template] = $cable_index_plugin[day_template]->GetChild('CABLE-Entry');
	if ($cable_index_plugin[entry_template] === false)
		return 'Error retrieving index entry template';
	
	$cable_index_plugin[category_template] = $cable_index_plugin[entry_template]->GetChild('CABLE-Category');
	if ($cable_index_plugin[category_template] === false)
		return 'Error retrieving index category template';

	/* strip out extracted blocks since we've already loaded them into discrete templates */
	$cable_index_plugin[month_template]->ReplaceChild('CABLE-Entry','',true);
	$cable_index_plugin[month_template]->Reset();
	$cable_index_plugin[day_template]->ReplaceChild('CABLE-Entry','',true);
	$cable_index_plugin[day_template]->Reset();
	$cable_index_plugin[entry_template]->ReplaceChild('CABLE-Category','',true);
	$cable_index_plugin[entry_template]->Reset();

	$cable_index_plugin[date_formats] = $connector->template->GetValue('CABLE-DateFormat',true);
	if (count($cable_index_plugin[date_formats]) == 0)
		$cable_index_plugin[date_formats] = array();
				
	$cable_index_plugin[category_delimiter] = $connector->template->GetValue('CABLE-CategoryDelimiter');

	/* sort array so that largest (ie latest) entries are first */
	if ($connector->config['IndexSort'] != 'descending')
		krsort($connector->data);
	
	/* if we're to restrict entries to only this month, strip out entries for other months */
	if (($connector->config['RestrictMonth'] == 1) && ($_REQUEST['feed'] == ''))
	{
		/* get the month of the first entry */
		list($first_entry) = array_slice($connector->data,0,1);
		$this_month = date('n',$first_entry[timestamp]);

		/* delete all entries not present in this month */
		$counter = 0;
		foreach($connector->data as $timestamp => $data)
		{
			if (date('n',$timestamp) != $this_month)
			{
				/* this doesn't work, due to being passed by reference: unset($connector->data[$timestamp]); */
				/* we have to set the "delete" field of the array, and then entry.php will know to remove it from the table */
				$connector->data[$timestamp][delete] = true;
			}
			else
				$last_entry[timestamp] = $timestamp;
				
			$counter++;
		}
	}
	else
	{
		list($first_entry) = array_slice($connector->data,0,1);
		list($last_entry) = array_slice($connector->data,-1,1);
	}
	
	/* set our internal day and month position keepers */
	$cable_index_plugin[current_day] = date('z',$first_entry[timestamp]);
	$cable_index_plugin[current_month] = date('n',$first_entry[timestamp]);

	/* get the next IndexEntries above ours */
	$entry_table = "cable_".$connector->config['TablePrefix']."_entries";
	$query = "SELECT timestamp FROM $entry_table WHERE (timestamp > ".$first_entry[timestamp].') AND (visible=1) ORDER BY timestamp ASC LIMIT '.$connector->config['IndexEntries'];
	if (($result = mysql_query($query,$connector->db_link)) === false)
		return 'Error accessing entry table';
		
	/* loop through the ever increasing timestamps to find the largest one still in this month */
	while (($row = mysql_fetch_row($result)) !== false)
	{
		if (date('n',$first_entry[timestamp]) == date('n',$row[0]))
			$cable_index_plugin[next_entry] = $row[0];
	}
	
	/* there's (at least one more) entry in this month */
	$pages = false;
	if ($cable_index_plugin[next_entry])
	{
		$pages = true;
		$connector->template->SetBool('CABLE-Pages.next',true);
	}
	else
		$connector->template->SetBool('CABLE-Pages.next',false);
	
	/* get the entry just below our last (earliest) entry */
	$query = "SELECT timestamp FROM $entry_table WHERE (timestamp < ".$last_entry[timestamp].") AND (visible=1) ORDER BY timestamp DESC LIMIT 1";
	if (($result = mysql_query($query,$connector->db_link)) === false)
		return 'Error accessing entry database';
	list($previous_entry) = mysql_fetch_row($result);
	
	if ((date('n',$last_entry[timestamp]) == date('n',$previous_entry)) && (date('n',$first_entry[timestamp]) == date('n',$previous_entry)))
	{
		$cable_index_plugin[previous_entry] = $previous_entry;
		$pages = true;
		$connector->template->SetBool('CABLE-Pages.previous',true);
	}
	else
		$connector->template->SetBool('CABLE-Pages.previous',false);
		
	$connector->template->SetBool('CABLE-Pages',$pages);

	/* return to previous sorting scheme if necessary */
	if ($connector->config['IndexSort'] != 'descending')
		ksort($connector->data);

	/* if we've made it this far, everything is OK */
	$cable_index_plugin[fail] = false;

	return true;
}

function cable_index(&$connector)
{
	global $cable_index_plugin;
		
	/* check to make sure everything is kosher */
	if($cable_index_plugin[fail])
		return true;
	
	/* plugin index routines aren't called for cached material */

	/* append this timestamp to our internal list */
	$cable_index_plugin[timestamps][] = $connector->data['timestamp'];
	
	/* START ENTRY REPLACEMENTS */
	
	// straight (dumb) replacements
	foreach($connector->data as $field => $value)
	{
		if (is_bool($value))
			$cable_index_plugin[entry_template]->SetBool('CABLE-Entry.'.$field,$value);
		elseif(!is_array($value))
			$cable_index_plugin[entry_template]->ReplaceInsert('CABLE-Entry.'.$field,stripslashes(rawurldecode($value)));
	}

	// entry url replacements 
	if ($connector->config['EnableModRewrite'] > 0)
		$cable_index_plugin[entry_template]->ReplaceInsert('CABLE-Entry.url', $connector->config[SiteURL].$connector->data[timestamp]);
	else
		$cable_index_plugin[entry_template]->ReplaceInsert('CABLE-Entry.url', $connector->config[SiteURL].'entry.php?t='.$connector->data[timestamp]);

	// date replacements
	foreach($cable_index_plugin[date_formats] as $i => $f)
		$cable_index_plugin[entry_template]->ReplaceInsert('CABLE-Entry.date.'.$i,date($f,$connector->data[timestamp]));
	$cable_index_plugin[entry_template]->ReplaceInsert('CABLE-Entry.num',$connector->data[counter] +1);
	
	/* retrive author name information */
	if (($ret = CABLE_indexAuthor($connector->data[author],$connector->db_link)) !== true)
		return $ret;
	
	// author replacements
	foreach ($cable_index_plugin[author_names][$connector->data[author]] as $f => $v)
		$cable_index_plugin[entry_template]->ReplaceInsert('CABLE-Entry.author.'.$f,$v);

	// category replacements
	$counter = 0;
	foreach($connector->data[category] as $category)
	{
		$cable_index_plugin[category_template]->Reset();
		$cable_index_plugin[category_template]->ReplaceInsert('CABLE-Category.name',$category);
		/* insert the delimiter between categories */
		if ($counter == 0)
			$cable_index_plugin[entry_template]->AppendInsert('CABLE-Entry.categories',$cable_index_plugin[category_template]->template);
		else
			$cable_index_plugin[entry_template]->AppendInsert('CABLE-Entry.categories',$cable_index_plugin[category_delimiter].$cable_index_plugin[category_template]->template);
		$counter++;
	}

	if ($connector->data[counter] == ($connector->data[num] -1)) /* is it the last time we're going to be run? */
	{
		if (($cable_index_plugin[current_day] != date('z',$connector->data['timestamp'])) && ($connector->data[num] > 1))
		{
			/* since we've moved on to another day, save the old day template */
			cable_indexIncrementDay($connector,$cable_index_plugin[timestamps][$connector->data[counter] -1]);
			
			/* if the month has incremented as well, save it too */
			if ($cable_index_plugin[current_month] != date('n',$connector->data['timestamp']))
				cable_indexIncrementMonth($connector,$cable_index_plugin[timestamps][$connector->data[counter] -1]);
		}
		
		/* save the currently open templates to the main template before we quit */
		cable_indexIncrementEntry();
		cable_indexIncrementDay($connector,$cable_index_plugin[timestamps][$connector->data[counter]]);
		cable_indexIncrementMonth($connector,$cable_index_plugin[timestamps][$connector->data[counter]]);
		
		return true;
	}
	elseif ($connector->data[counter] > 0) /* don't increment on our first execution */
	{
		/* same as above, but without the final bail save */
		if ($cable_index_plugin[current_day] != date('z',$connector->data['timestamp']))
		{
			cable_indexIncrementDay($connector,$cable_index_plugin[timestamps][$connector->data[counter] -1]);
			if ($cable_index_plugin[current_month] != date('n',$connector->data['timestamp']))
				cable_indexIncrementMonth($connector,$cable_index_plugin[timestamps][$connector->data[counter] -1]);
		}
	}
	
	/* save the entry to the template */
	cable_indexIncrementEntry();
	
	/* update our internal day and month position keepers */
	$cable_index_plugin[current_day] = date('z',$connector->data[timestamp]);
	$cable_index_plugin[current_month] = date('n',$connector->data[timestamp]);
	
	return true;
}

function cable_indexIncrementEntry()
{
	/* saves the current entry template to the day template */
	global $cable_index_plugin;
	
	$cable_index_plugin[day_template]->AppendInsert('CABLE-Entries',$cable_index_plugin[entry_template]->template);
	$cable_index_plugin[entry_template]->Reset();
	
	return null;
}
function cable_indexIncrementDay($connector,$t)
{
	/* saves the current day template to the month template, and makes date appropriate substitutions */
	global $cable_index_plugin;

	foreach($cable_index_plugin[date_formats] as $i => $f)
		$cable_index_plugin[day_template]->ReplaceInsert('CABLE-Day.date.'.$i,date($f,$t));
	
	$cable_index_plugin[month_template]->AppendInsert('CABLE-Days',$cable_index_plugin[day_template]->template);
	$cable_index_plugin[day_template]->Reset();
	
	return null;
}

function cable_indexIncrementMonth(&$connector,$t)
{
	/* saves the current month template to the main template, and makes date appropriate substitutions */
	global $cable_index_plugin;

	foreach($cable_index_plugin[date_formats] as $i => $f)
		$cable_index_plugin[month_template]->ReplaceInsert('CABLE-Month.date.'.$i,date($f,$t));
	
	$connector->template->AppendInsert('CABLE-Months',$cable_index_plugin[month_template]->template);
	$cable_index_plugin[month_template]->Reset();
	
	return null;
}	

function cable_index_close(&$connector)
{
	global $cable_index_plugin;
	
	if($cable_index_plugin[fail])
		return true;
		
	if (!$connector->data[cached])
	{	
		/* do navigation stuff */
		if (($ret = CABLE_indexNavigation($connector)) !== true)
			return $ret;
			
		/* do standard date replacements */
		foreach($cable_index_plugin[date_formats] as $i => $f)
			$connector->template->ReplaceInsert('CABLE-Calendar.date.'.$i,date($f,$connector->timestamp));

		/* do top level replacements */
		$connector->template->ReplaceInsert('CABLE-Site.name',$connector->config[SiteName]);
		$connector->template->ReplaceInsert('CABLE-Base.url',$connector->config[SiteURL]);
		$connector->template->ReplaceInsert('CABLE-Files.url',$connector->config[SiteURL].'files/'.$connector->config[ThemeName].'/');
		$connector->template->ReplaceInsert('CABLE-CSS.url',$connector->config[SiteURL].'css/'.$connector->config[ThemeName].'/');
	
		/* save non-specific information to the template original */
		$connector->template->Cache();
	
		/* free up memory */
		unset($cable_index_plugin);
	}

	/* set user info */
	$connector->template->SetBool('CABLE-User.loggedin',$connector->user->logged_in);
	$connector->template->SetBool('CABLE-User.isadmin',$connector->user->is_admin);
	$permissible = array('username','fullname','firstname','lastname');
	foreach($connector->user->values as $f => $v)
		if (in_array($f,$permissible))
			$connector->template->ReplaceInsert('CABLE-User.'.$f,$v);

	return true;
}

function CABLE_indexNavigation(&$connector)
{
	global $cable_index_plugin;
		
	if ($cable_index_plugin[connector]->config['EnableModRewrite'] > 0)
	{
		$connector->template->ReplaceInsert('CABLE-Nav.prev.url',$connector->config[SiteURL].'index/'.$cable_index_plugin[previous_entry]);
		$connector->template->ReplaceInsert('CABLE-Nav.prevyear.url',$connector->config[SiteURL].'index/'.mktime(12,60,60,12,31,date('Y',$connector->timestamp)-1));
		$connector->template->ReplaceInsert('CABLE-Nav.prevmonth.url',$connector->config[SiteURL].'index/'.mktime(12,60,60,1,date('n',$connector->timestamp)-1),date('Y',$connector->timestamp));
		$connector->template->ReplaceInsert('CABLE-Nav.latest.url',$connector->config[SiteURL].'index/'.time());
		$connector->template->ReplaceInsert('CABLE-Nav.next.url',$connector->config[SiteURL].'index/'.$cable_index_plugin[next_entry]);
		$connector->template->ReplaceInsert('CABLE-Nav.nextmonth.url',$connector->config[SiteURL].'index/'.mktime(0,0,0,1,date('n',$connector->timestamp)+1),date('Y',$connector->timestamp));
		$connector->template->ReplaceInsert('CABLE-Nav.nextyear.url',$connector->config[SiteURL].'index/'.mktime(0,0,0,1,1,date('Y',$connector->timestamp)+1));
	}
	else
	{
		$connector->template->ReplaceInsert('CABLE-Nav.prev.url',$connector->config[SiteURL].'index.php?t='.$cable_index_plugin[previous_entry]);
		$connector->template->ReplaceInsert('CABLE-Nav.prevmonth.url',$connector->config[SiteURL].'index.php?t='.mktime(12,60,60,1,date('n',$connector->timestamp)-1),date('Y',$connector->timestamp));
		$connector->template->ReplaceInsert('CABLE-Nav.prevyear.url',$connector->config[SiteURL].'index.php?t='.mktime(12,60,60,12,31,date('Y',$connector->timestamp)-1));
		$connector->template->ReplaceInsert('CABLE-Nav.latest.url',$connector->config[SiteURL].'index.php?t='.time());
		$connector->template->ReplaceInsert('CABLE-Nav.nextmonth.url',$connector->config[SiteURL].'index.php?t='.mktime(0,0,0,1,date('n',$connector->timestamp)+1),date('Y',$connector->timestamp));
		$connector->template->ReplaceInsert('CABLE-Nav.next.url',$connector->config[SiteURL].'index.php?t='.$cable_index_plugin[next_entry]);
		$connector->template->ReplaceInsert('CABLE-Nav.nextyear.url',$connector->config[SiteURL].'index.php?t='.mktime(0,0,0,1,1,date('Y',$connector->timestamp)+1));
	}

	$month_template = $connector->template->GetChild('CABLE-NavMonth');
	$connector->template->ReplaceChild('CABLE-NavMonth','');
	if ($month_template === false)
		return 'Error retrieving month navigation template';
		
	for($i=1; $i <= 12; $i++)
	{
		$month_timestamp = mktime(0,0,0,$i,15,date('Y',$connector->timestamp));
		$month_timestamp = mktime(23,59,59,$i,date('t',$month_timestamp),date('Y',$connector->timestamp));

		$month_template->SetBool('CABLE-Nav.month.current',(bool)($i == date('n',$connector->timestamp)));

		foreach($cable_index_plugin[date_formats] as $j => $f)
			$month_template->ReplaceInsert('CABLE-Nav.month.date.'.$j,date($f,$month_timestamp));

		if ($cable_index_plugin[connector]->config['EnableModRewrite'] > 0)
			$month_template->ReplaceInsert('CABLE-Nav.month.url',$connector->config[SiteURL].'index/'.$month_timestamp);
		else
			$month_template->ReplaceInsert('CABLE-Nav.month.url',$connector->config[SiteURL]."index.php?t=$month_timestamp");

		$month_html = $month_html.$month_template->Render();
		$month_template->Reset();
	}
	
	$connector->template->ReplaceInsert('CABLE-NavMonths',$month_html);
	
	return true;
}

function CABLE_indexAuthor($a,$db_link)
{
	global $cable_index_plugin;
	
	if($cable_index_plugin[fail])
		return true;
	
	/* retrieve author information from database and save into array */
	if (!$cable_index_plugin[author_names][$a])
	{
		$user_table = "cable_".$cable_index_plugin[connector]->config['TablePrefix']."_users";
		$query = "SELECT username,fullname FROM $user_table WHERE (username = '$a') LIMIT 1";
		if ((($result = mysql_query($query,$db_link)) !== false) && (mysql_num_rows($result) == 1))
		{
			$cable_index_plugin[author_names][$a] = mysql_fetch_assoc($result);
			list(
				$cable_index_plugin[author_names][$a]['firstname'],
				$cable_index_plugin[author_names][$a]['lastname']
			) = explode(' ',$cable_index_plugin[author_names][$a]['fullname']);
		}
		else /* something went to shit */
			return 'Error accessing author table.';
	}
	
	return true;
}

?>